package main

import (
	"api/go-demo/config"
	"api/go-demo/handlers"
	"api/go-demo/middlewares"
	"api/go-demo/utils"
	"flag"
	"logging"
	"runtime"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

var (
	tomlFile = flag.String("config", "docs/test.toml", "config file")
)

// init 初始化配置
func init() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	gin.SetMode(gin.ReleaseMode)
}

func main() {
	flag.Parse()

	// 解析配置文件
	tomlConfig, err := config.UnmarshalConfig(*tomlFile)
	if err != nil {
		logging.Errorf("UnmarshalConfig: err:%v\n", err)
	}

	// 绑定路由，及公共的tomlConfig
	router := gin.New()
	router.Use(cors.New(cors.Config{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"GET", "PUT", "POST", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"x-fxb-jwt", "Content-Type", "Origin", "Content-Length"},
		ExposeHeaders:    []string{"x-fxb-jwt"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	}))
	router.Use(gin.Recovery())
	router.Use(middlewares.Config(tomlConfig))

	router.Use(middlewares.Gorm(utils.DBAUTHORITY, tomlConfig))
	// 路由配置
	router.GET("/", handlers.Index) // 首页
	v1 := router.Group("/v1")       // v1

	// token鉴权
	v1.Use(middlewares.Auth())
	v1.Use(middlewares.LogRequest(tomlConfig))
	// 系统管理
	{
		v1.POST("/sys/findPerMenuTree", handlers.OnFindPerMenuTreeRequest) // 查询菜单树
	}

	logging.Debugf("run filecenter at:%v\n", tomlConfig.GetListenAddr())

	router.Run(tomlConfig.GetListenAddr())
}
